﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using BySoft.Web.Utility;
using BySoft.Server.Common;
using BySoft.Server.Consts;
using BySoft.Server.Common.Entity;
using BySoft.Server.Business;
using BySoft.Server.Common.Enum;
using OneSoft.EntityCore;
using System.Web;
using BySoft.Web.Site;

namespace BySoft.Web.Site.SysManage
{
    public partial class FormAuditEdit : AuthBasePage
    {
        #region 属性定义
        private string m_strsequenceName = "SysFormaudit";

        private DataTable DtFormAuditData
        {
            get
            {
                if (null == Session["FormAuditData"])
                {
                    return CreateDT();
                }
                else
                {
                    return (DataTable)Session["FormAuditData"];
                }
            }
            set
            {
                Session["FormAuditData"] = value;
            }
        }

        private DataTable CreateDT()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("FormAuditDetailID");//0
            dt.Columns.Add("CheckUser");//1
            dt.Columns.Add("OrderNum");//2
            return dt;
        }
        #endregion

        #region 初始化及绑定控件
        private void InitData()
        {
			DtFormAuditData = null;
			SetControlAttr(new SysFormauditEntity(), tBase);
            
			string strCode = HttpUtility.UrlDecode(UIHelper.GetQueryStringValue("id").Trim());
			InitHead(strCode);
            InitBody(strCode);
        }

		private void InitHead(string strCode)
        {
            DataTable dt = SysFormcheck.SelectHead(strCode); 
            DataRow row = dt.Rows[0];
            chkIsCheck.Checked = CommonMethod.GetString(row["IsCheck"]).Equals("1");
            DataTable dttemp = CreateDT();
            foreach (DataRow dr in dt.Rows)
            { 
                DataRow rowNew = dttemp.NewRow();
                rowNew["FormCheckDetailID"] = GetGridViewString(dr[""]);
                rowNew["CheckUser"] = GetGridViewString(ddlCheckUser);
                rowNew["OrderNum"] = GetGridViewString(txtOrderNum); 
                dttemp.Rows.Add(rowNew);
            }
            dttemp.AcceptChanges();
            DtFormAuditData = dttemp;

        }

        private void InitBody(string strCode)
        {
            DataTable dt = SysFormaudit.SelectBody(strCode);
            DataTable dttemp = CreateDT();
            DtFormAuditData = CommonMethod.CopyDTtoDT(dt, dttemp);
            BindData();
        }
        #endregion

        #region 控件事件
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                grdResult.Style.Add("word-break", "keep-all");
                grdResult.Style.Add("word-wrap", "normal");
                InitData();
            }
            Master.ValidationGroup = "gSubmit";
            UIHelper.RunScript(this.UpdatePanel1, "Refreashtab();");
        }

        private void GetGridViewData()
        {
            DataTable dttemp = CreateDT();
            foreach (GridViewRow gvr in grdResult.Rows)
            {
                Label lblFormAuditDetailID = gvr.FindControl("lblFormAuditDetailID") as Label;
                if (lblFormAuditDetailID == null || string.IsNullOrEmpty(lblFormAuditDetailID.Text.Replace("&nbsp;", "")))
                {
                    continue;
                }
                DropDownList ddlCheckUser = gvr.FindControl("ddlCheckUser") as DropDownList;
                TextBox txtOrderNum = gvr.FindControl("txtOrderNum") as TextBox;


                DataRow row = dttemp.NewRow();
                row["FormCheckDetailID"] = GetGridViewString(lblFormAuditDetailID);
                row["CheckUser"] = GetGridViewString(ddlCheckUser);
                row["OrderNum"] = GetGridViewString(txtOrderNum);


                dttemp.Rows.Add(row);
            }
            dttemp.AcceptChanges();
            DtFormAuditData = dttemp;
        }

        private void BindData()
        {
            if (DtFormAuditData.Rows.Count > 0)
            {
                grdResult.DataSource = DtFormAuditData;
                grdResult.DataBind();
                SetControlAttr(new SysFormauditdetailEntity(), grdResult);
            }
            else
            {
                UIHelper.BindEmptyGridView(grdResult, CreateDT());
            }
            UIHelper.RunScript(this.UpdatePanel1, "iframeAutoFit();");
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            GetGridViewData();
            DataTable dttemp = DtFormAuditData.Copy();
            DataRow row = dttemp.NewRow();
            row["FormCheckDetailID"] = "-1";
            row["OrderNum"] = dttemp.Rows.Count + 1;
            dttemp.Rows.Add(row);
            DtFormAuditData = dttemp;
            BindData();
        }

        protected void btnAddh_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected DataTable BindCheckUser()
        {
            DataTable dt = SysUser.Select();
            DataRow row = dt.NewRow();
            row["UserID"] = "";
            row["UserName"] = "请选择...";
            dt.Rows.Add(row);
            return dt;
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!ValidateData())
            {
                return;
            }

            SysFormauditEntity entity = new SysFormauditEntity();
            entity.FormAuditID = lblFormAuditID.Text;
            //entity.ModuleID = ddlModuleID.SelectedValue;
            entity.IsCheck = chkIsCheck.Checked ? "1" : "0";
            entity.CreateUserId = CurrentUser.UserID;
            entity.CreateUserName = CurrentUser.UserName;
            entity.CreateDate = DateTime.Now;
            entity.ModifyUserId = CurrentUser.UserID;
            entity.ModifyUserName = CurrentUser.UserName;
            entity.ModifyDate = DateTime.Now;


            List<SysFormauditdetailEntity> lstbody = new List<SysFormauditdetailEntity>();
            foreach (GridViewRow gvr in grdResult.Rows)
            {
                Label lblFormAuditDetailID = gvr.FindControl("lblFormAuditDetailID") as Label;
                if (lblFormAuditDetailID == null || string.IsNullOrEmpty(lblFormAuditDetailID.Text.Replace("&nbsp;", "")))
                {
                    continue;
                }
                DropDownList ddlCheckUser = gvr.FindControl("ddlCheckUser") as DropDownList;
                TextBox txtOrderNum = gvr.FindControl("txtOrderNum") as TextBox;


                SysFormauditdetailEntity entbody = new SysFormauditdetailEntity();
                entbody.FormAuditDetailID = Convert.ToDecimal(lblFormAuditDetailID.Text);
                entbody.FormAuditID = lblFormAuditID.Text;
                entbody.CheckUser = ddlCheckUser.SelectedValue;
                entbody.OrderNum = Convert.ToInt32(txtOrderNum.Text);

                lstbody.Add(entbody);
            }

            SysFormaudit.SaveOrUpdate(entity, "Update", lstbody);
            base.LogAction(BaseEnum.ActionType.Modify, entity.FormAuditID, true, null, new EntityBase[] { entity });
            DtFormAuditData = null;
            UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../SysManage/FormAuditList.aspx");
        }

        protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "del")
            {
                string str = e.CommandArgument.ToString();
                int iDel = CommonMethod.ConvertToInt(str);
                GetGridViewData();
                DataTable dt = DtFormAuditData.Copy();
                dt.Rows.RemoveAt(iDel);
                DtFormAuditData = dt.Copy();
                BindData();
                UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
            }
        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                #region 删除绑定
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete +

        "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
                #endregion

                string strCheckUser = ((DataTable)((GridView)sender).DataSource).Rows[e.Row.RowIndex]["CheckUser"].ToString().Trim();
                DropDownList ddlCheckUser = e.Row.FindControl("ddlCheckUser") as DropDownList;
                if (ddlCheckUser != null)
                {
                    ddlCheckUser.SelectedValue = strCheckUser;
                }
            }
        }
        #endregion

        #region 本地方法
        private bool ValidateData()
        {
            string strMention = "";

            string strOriMainKey = UIHelper.GetQueryStringValue("id").Trim();
            if (!string.IsNullOrEmpty(strOriMainKey))
            {
                if (lblFormAuditID.Text != strOriMainKey)
                {
                    if (ClsComm.CheckExist("SYS_FormAudit", "FormAuditID", lblFormAuditID.Text.Trim(), true))
                    {
                        strMention = "表单审核管理编号已经存在！<br />";
                        ClsComm.SetMaxSequenceID(m_strsequenceName);
                    }
                }
            }
            else
            {
                if (ClsComm.CheckExist("SYS_FormAudit", "FormAuditID", lblFormAuditID.Text.Trim(), true))
                {
                    strMention = "表单审核管理编号已经存在！<br />";
                    ClsComm.SetMaxSequenceID(m_strsequenceName);
                }
            }

            if (string.IsNullOrEmpty(strMention))
            {
                return true;
            }
            else
            {
                UIHelper.AlertMessage(this.Page, strMention);
                return false;
            }
        }
        #endregion
    }
}

